package com.fudan.backend.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fudan.backend.exception.BaseException;
import com.fudan.backend.exception.RetCode;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    //token过期时间
    private static final long time = 1000L * 60L * 60L;
    //签名密钥
    private static final String signature = "sig";

    public static String createToken(String userId, String username, int role){
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withClaim("role", role)
                .withExpiresAt(new Date(System.currentTimeMillis()+time))
                .sign(Algorithm.HMAC256(signature));
        return token;
    }

    /**
     * 验证token是否有效
     * @param token
     * @return false 无效token，true有效
     */
    public static boolean checkToken(String token) throws BaseException {
        DecodedJWT jwt=null;
        try {
            JWTVerifier verifier=JWT.require(Algorithm.HMAC256(signature)).build();
            jwt=verifier.verify(token);
        }catch (Exception e){
            throw new BaseException(RetCode.INVALID_TOKEN.getCode(), RetCode.INVALID_TOKEN.getMessage());
        }
        return true;
    }

    /**
     * 获取token中保存的claim
     * @param token
     * @return token中保存的role，若失败则返回-1
     */
    public static Integer getRole(String token) throws BaseException {
        JWTVerifier verifier=JWT.require(Algorithm.HMAC256(signature)).build();
        DecodedJWT jwt = null;
        try{
            jwt = verifier.verify(token);
        }
        catch (Exception e){
            throw new BaseException(RetCode.INVALID_TOKEN.getCode(), RetCode.INVALID_TOKEN.getMessage());
        }
        return jwt.getClaim("role").asInt();
    }

    /**
     * 解析token中的id
     */
    public static String getUserId(String token) throws BaseException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(signature)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new BaseException(RetCode.INVALID_TOKEN.getCode(), RetCode.INVALID_TOKEN.getMessage());
        }
        return jwt.getClaim("userId").asString();
    }
}
